/*
 * Copyright 2011-2011 Tiago da Fonseca Frazao  All rights reserved.
 */

package mz.co.research.shared.model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

/**
 * @author Tiago da Fonseca Frazao
 */
@Entity
@Table(name = "FORM")
public class Form extends UpdatableEntity {

	@NotNull
	@Column(name = "CODE", length = 25, nullable = false)
	private String code;

	@NotNull
	@Size(max = 255)
	@Column(name = "DESCRIPTION", length = 255, nullable = true)
	private String description;

	@ManyToOne
	@JoinColumn(name = "FK_RESEARCH_ID", nullable = false)
	private Research research;

	@OneToMany(mappedBy = "form", cascade = CascadeType.PERSIST)
	private List<Question> questions = new ArrayList<Question>();

	@Transient
	private Map<String, Question> questionMap = new HashMap<String, Question>();

	/**
	 * @return the code
	 */
	public String getCode() {
		return code;
	}

	/**
	 * @param code
	 *            the code to set
	 */
	public void setCode(String code) {
		this.code = code;
	}

	/**
	 * @return the description
	 */
	public String getDescription() {
		return description;
	}

	/**
	 * @param description
	 *            the description to set
	 */
	public void setDescription(String description) {
		this.description = description;
	}

	/**
	 * @param the
	 *            question to add
	 */
	public void addQuestion(Question question) {
		question.setForm(this);
		this.questions.add(question);
		this.questionMap.put(question.getDescription(), question);
	}

	/**
	 * @param question
	 *            the question to remove
	 */
	public void removeQuestion(Question question) {
		this.questions.remove(question);
		this.questionMap.remove(question.getDescription());
	}

	/**
	 * @return
	 */
	public List<Question> getQuestions() {
		return questions;
	}

	/**
	 * @param code
	 * @return
	 */
	public Question getQuestion(String code) {
		return this.questionMap.get(code);
	}

	/**
	 * @return the research
	 */
	public Research getResearch() {
		return research;
	}

	/**
	 * @param research
	 *            the research to set
	 */
	public void setResearch(Research research) {
		this.research = research;
	}

	@Override
	public String toString() {
		StringBuilder buffer = new StringBuilder("\nForm");

		buffer.append(super.toString());

		buffer.append("\ncode        :" + this.code);
		buffer.append("\ndescription :" + this.description);

		return buffer.toString();
	}
}
